<?php  
class ProductModel extends Model{
	public $table='product';//货品表
	/**
	 * 获取商品属性
	 * @param  integer $goods_gid [description]
	 * @return [type]             [description]
	 */
	public function getAttr($goods_gid=0){
		//如果没传值 就Q()获取
		$goods_gid=$goods_gid ? $goods_gid : Q('goods_gid',0,'intval');

		$sql="SELECT * FROM shop_attribute a JOIN shop_goods_attr ga ON a.attr_id=ga.attr_id WHERE goods_gid=$goods_gid AND attr_type=1 ORDER BY a.attr_id ASC";
		//联表查询（属性表  商品属性表）
		$data=M()->query($sql);

		//定义空数组 储存获取的商品属性
		$attr=array();

		foreach ($data as $d) {
			//按属性id来分类 同类的放一起  如：都是颜色的  id相同  放一起
			$attr[$d['attr_id']][]=$d;
		}
		
		return $attr;
	}
	/**
	 * 获取指定商品的货品信息
	 * @param  integer $goods_gid [商品id]
	 * @return [type]             [description]
	 */
	public function getProduct($goods_gid=0){
		//如果没传值 就Q()获取
		$goods_gid=$goods_gid ? $goods_gid : Q('goods_gid',0,'intval');

		$product=$this->where("goods_gid=$goods_gid")->order("product_id desc")->all();
		
		foreach ($product as $id => $p) {
			
			$map['id']=array('IN',explode('-', $p['goods_attr_id']));
			// p($map);
			$goods_attr_str=M('goods_attr')->where($map)->order('attr_id asc')->getField("attr_value",true);
			// p($goods_attr_str);exit;
			$product[$id]['goods_attr_str']=$goods_attr_str;
			
		}
		
		return $product;
	}

	/**
	 * 添加货品
	 */
	public function addProduct(){
		
		$attrId=array();

		//处理传递过来的商品属性id值
		foreach ($_POST['attr'] as $a) {

			foreach ($a as $n => $id) {
				
				$attrId[$n][]=$id;
			}
		}
		
		//循环处理好的数组
		foreach ($attrId as $k => $a) {
			
			//未选择属性时值为0  不添加
			if (array_search(0, $a) !== false) {
				//跳出当前循环
				continue;
			}
			
			// //货号与货品数量为空时，不添加
			if (empty($_POST['product_sn'][$k]) || empty($_POST['product_number'][$k])) {
				//跳出当前循环
				continue;
			}
			
			$data=array();
			//组合要添加的数据
			$data['goods_gid']=$_POST['goods_gid'];
			$data['goods_attr_id']=implode('-', $a);
			$data['product_sn']=$_POST['product_sn'][$k];
			$data['product_number']=$_POST['product_number'][$k];
			
			//添加数据
			if (!$this->add($data)) {
				$this->error="操作失败";
			}
		}
		
		return true;
	}

	/**
     * 删除货品
     * @return bool
     */
    public function delPoduct(){

        $product_id = Q('product_id', 0, 'intval');

        if (!$product_id) {

            $this->error = '货品不存在';
            return false;
        }

        return $this->del($product_id);
    }
}
?>